package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: dw
 * @Date 2022/3/16 22:34
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private HttpSession session;

    @Autowired(required = false)
    private UserService userService;

    //注入redisTemplate(用于缓存技术)
    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map){
        //接收数据封装到map中
        String phone = map.get("phone");
        String code = map.get("code");
        //从会话域中获取生成的验证码
        //String sessionCode = (String) session.getAttribute(phone);

        //从缓存里面获取验证码
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);

        //调用业务层判断
        User loginUser = userService.login(phone, code, sessionCode);
        if (loginUser!=null) {
            //登录用户有效，将用户id上传到会话域中
            session.setAttribute("user",loginUser.getId());
            //登录成功后删除会话域中的验证码
            //session.removeAttribute(phone);

            //将缓存中的验证码删除
            redisTemplate.delete(phone);
        }
        return R.success(loginUser);
    }



    //处理发送短信的请求
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        //1.接收手机号封装User对象
        //2.生成4位手机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码："+code);
        //3.发送手机验证码,注释调用阿里云的短信发送代码
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972",user.getPhone(),code);
        //4.将生成的验证码存储到session中（手机号作为key，验证码作为value）
        //session.setAttribute(user.getPhone(),code);

        //将验证码存储到缓存中，并设置过期时间5分钟
        redisTemplate.opsForValue().set(user.getPhone(),code,300, TimeUnit.SECONDS);
        //5.返回数据，输出成功
        return R.success("发送验证码短信成功");
    }
}
